<template>
  <el-dialog
    ref="dialog"
    title="关联图纸"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="80%"
    @close="cancelHandle"
  >
    <el-tabs v-model="activeName" @tab-click="changeTab">
      <el-tab-pane label="全部" name="all">
        <div class="table-list-box">
          <el-table
            ref="multipleTable"
            v-loading="tableLoading"
            :data="tableData"
            border
            height="160"
            header-row-class-name="table-list-header"
            :row-class-name="tableRowClassName"
            tooltip-effect="dark"
            style="width: 100%"
            @row-click="selectRow"
            @select="selectTable"
            @select-all="selectionAll"
            @selection-change="selectChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="picTaskCode" label="图纸编码" show-overflow-tooltip min-width="100" />
            <el-table-column prop="picType" label="图纸类型" show-overflow-tooltip min-width="100">
              <template slot-scope="scope">
                <span>{{ formaterData(picChangeTypeList, scope.row.picType) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="designRange" label="设计范围" show-overflow-tooltip min-width="120">
              <template slot-scope="scope">
                <span>{{ formaterArr(designRangeList, scope.row.designRange) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="decorationType" label="装修形式" show-overflow-tooltip min-width="100">
              <template slot-scope="scope">
                <span>{{ formaterArr(decorationTypeList, scope.row.decorationType) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="designSpace" label="设计区域" show-overflow-tooltip min-width="100">
              <template slot-scope="scope">
                <span>{{ formaterArr(areaList, scope.row.designSpace) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="designBizType" label="设计业务类型" show-overflow-tooltip min-width="120">
              <template slot-scope="scope">
                <span>{{ formaterArr(designBizTypeList, scope.row.designBizType) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="picTotalArea" label="设计总面积" min-width="100" show-overflow-tooltip />
            <el-table-column prop="softwareSumArea" label="软体区面积" min-width="100" show-overflow-tooltip />
            <el-table-column prop="suiteSumArea" label="套房区面积" min-width="100" show-overflow-tooltip />
            <el-table-column prop="haveEAndC" label="是否含成融定" min-width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ formaterData(booleansList1, scope.row.haveEAndC) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="eandCArea" label="成融定面积" min-width="100" show-overflow-tooltip />
            <el-table-column prop="newBusinessAreaSummary" label="新业务面积汇总" min-width="110" show-overflow-tooltip />
            <!-- <el-table-column prop="overCupboardArea" label="橱柜面积" min-width="80" />
        <el-table-column prop="bathroomArea" label="卫浴面积" min-width="80" />
        <el-table-column prop="modelRoomArea" label="样板间面积" min-width="80" /> -->
            <el-table-column prop="expectEndTime" label="预计设计完成时间" min-width="120" show-overflow-tooltip />
            <el-table-column prop="designUnitName" label="设计单位" min-width="80" show-overflow-tooltip />
            <el-table-column prop="designerName" label="设计师" min-width="80" show-overflow-tooltip />
            <el-table-column prop="schedule" label="图纸进度" min-width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ formaterData(scheduleList, scope.row.schedule) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="state" label="图纸状态" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ formaterData(stateList, scope.row.state) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-box">
          <div class="pagination-container">
            <el-pagination
              :current-page.sync="currentPage"
              :page-sizes="pageSizelist"
              :page-size="pageSize"
              layout="sizes, prev, pager, next, slot"
              :total="allTotal === 0 ? total : allTotal"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            >
              <span class="el-pagination__jump">前往
                <el-input-number
                  v-model="jumpPage"
                  :controls="false"
                  :min="1"
                  @blur="showEnter"
                  @keyup.enter.native="showEnter"
                />页</span>
            </el-pagination>
            <div v-show="total <= pageSize" class="pagination-info">当前显示
              <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
              <span class="total"> {{ tableData.length }} </span> 条记录
            </div>
            <div v-show="total > pageSize" class="pagination-info">当前显示
              <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
              <span :class="[allTotal === 0 && total !== 0 ? 'total next-page': 'total']" @click="newEnter"> {{ allTotal === 0 && total !== 0 ? total-1 +'+': allTotal }}  </span> 条记录
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="`已选择(${selectedData.length})`" name="selected">
        <div class="table-list-box">
          <el-table
            ref="chosenTable"
            :data="selectedData"
            border
            height="160"
            header-row-class-name="table-list-header"
            highlight-current-row
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column prop="picTaskCode" label="图纸编码" show-overflow-tooltip min-width="100" />
            <el-table-column prop="picChangeType" label="图纸类型" show-overflow-tooltip min-width="100">
              <template slot-scope="scope">
                <span>{{ formaterData(picChangeTypeList, scope.row.picType) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="designRange" label="设计范围" show-overflow-tooltip min-width="120">
              <template slot-scope="scope">
                <span>{{ formaterArr(designRangeList, scope.row.designRange) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="decorationType" label="装修形式" show-overflow-tooltip min-width="100">
              <template slot-scope="scope">
                <span>{{ formaterArr(decorationTypeList, scope.row.decorationType) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="designSpace" label="设计区域" show-overflow-tooltip min-width="100">
              <template slot-scope="scope">
                <span>{{ formaterArr(areaList, scope.row.designSpace) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="designBizType" label="设计业务类型" show-overflow-tooltip min-width="120">
              <template slot-scope="scope">
                <span>{{ formaterArr(designBizTypeList, scope.row.designBizType) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="picTotalArea" label="设计总面积" min-width="100" show-overflow-tooltip />
            <el-table-column prop="softwareSumArea" label="软体区面积" min-width="100" show-overflow-tooltip />
            <el-table-column prop="suiteSumArea" label="套房区面积" min-width="100" show-overflow-tooltip />
            <el-table-column prop="haveEAndC" label="是否含成融定" min-width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ formaterData(booleansList1, scope.row.haveEAndC) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="eandCArea" label="成融定面积" min-width="100" show-overflow-tooltip />
            <el-table-column prop="newBusinessAreaSummary" label="新业务面积汇总" min-width="110" show-overflow-tooltip />
            <!-- <el-table-column prop="allCustomizedArea" label="定制面积" min-width="80" />
        <el-table-column prop="overCupboardArea" label="橱柜面积" min-width="80" />
        <el-table-column prop="bathroomArea" label="卫浴面积" min-width="80" />
        <el-table-column prop="modelRoomArea" label="样板间面积" min-width="80" /> -->
            <el-table-column prop="expectEndTime" label="预计设计完成时间" min-width="120" show-overflow-tooltip />
            <el-table-column prop="designUnitName" label="设计单位" min-width="80" show-overflow-tooltip />
            <el-table-column prop="designerName" label="设计师" min-width="80" show-overflow-tooltip />
            <el-table-column prop="schedule" label="图纸进度" min-width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ formaterData(scheduleList, scope.row.schedule) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="state" label="图纸状态" width="120">
              <template slot-scope="scope">
                <span>{{ formaterData(stateList, scope.row.state) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="color:#3dc094; cursor: pointer;"
                  @click="deleteChose(scope.$index,scope.row)"
                >删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- <div style="margin:10px 0;display:inlnk-black;font-size: 14px;">已选择
      <span style="color:#0f3eea;">{{ selectedData.length }}</span>条数据
    </div> -->

    <div slot="footer">
      <el-button size="mini" @click="cancelHandle">取 消</el-button>
      <el-button type="primary" size="mini" @click="submitPicData">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getDictByPatchType } from '@/api/dataDict'
import { queryPicTableData } from '@/api/proConfig'
import { getAreaData } from '../../components/index'
export default {
  name: 'RelevanceDrawing',
  props: {
    title: {
      type: String,
      default: '关联图纸11'
    },
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      activeName: 'all',
      booleansList1: [
        { dictCode: 1, dictName: '是' },
        { dictCode: 0, dictName: '否' }
      ],
      areaList: [],
      booleansList: [],
      picChangeTypeList: [],
      designRangeList: [],
      decorationTypeList: [],
      designSpaceList: [],
      designBizTypeList: [],
      scheduleList: [],
      stateList: [],
      queryObj: {},
      otherFilters: [],
      selectedData: [],
      tableData: [],
      pageSize: 5,
      pageSizelist: [5, 10, 15, 20],
      currentPage: 1,
      total: '',
      jumpPage: '',
      allTotal: 0,
      modelOtherFilter: []
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.selectedData = []
          this.$nextTick(() => {
            this.$refs.multipleTable.clearSelection()
          })
        }
      }
    }
  },
  async created() {
    await this.getDictByPatchTypeAll(['BOOLEANS', 'PIC_TYPE', 'DECORATION_RANGE', 'DECORATION_FORM', 'BELONG_REGION', 'BIZ_TYPE', 'PIC_DESIGN_SCHEDULE', 'PIC_DESIGN_STATE']).then(res => {
      this.picChangeTypeList = res.PIC_TYPE // 图纸类型
      this.designRangeList = res.DECORATION_RANGE // 设计范围
      this.decorationTypeList = res.DECORATION_FORM // 装修形式
      this.designSpaceList = res.BELONG_REGION // 设计区域
      this.designBizTypeList = res.BIZ_TYPE // 设计业务类型
      this.scheduleList = res.PIC_DESIGN_SCHEDULE // 图纸进度
      this.stateList = res.PIC_DESIGN_STATE // 图纸状态
      this.booleansList = res.BOOLEANS // 图纸状态
    })
    this.areaList = await getAreaData()
    this.queryObj = this.detailData
    this.otherFilters = this.getCondition(this.queryObj.proConfigType)
    this.getAllTableData(this.currentPage, this.pageSize, false, this.otherFilters)
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      if (!arr.length) return
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    formaterArr(data, str) {
      if (!data || !data.length || !str || !str.length) return
      let list = []
      if (typeof (str) === 'string') {
        list = str.split(',')
      } else {
        list = str
      }
      const arr = []
      data.forEach((item) => {
        const flag = list.some(v => v === item.dictCode)
        if (flag) {
          arr.push(item.dictName)
        }
      })
      return arr.toString()
    },
    getCondition(type) {
      let picType = ''
      let designSpace = ''
      if (type === 'FINISHED') {
        picType = 'BC'
        designSpace = '[Q014, Q015]'
      } else if (type === 'SANITARY') { // 卫浴
        picType = 'BC'
        designSpace = '[Q004, Q005]'
      } else if (type === 'CUSTOMIZE') {
        picType = 'BC'
      } else if (type === 'MATCHED_FINISHED') {
        picType = 'BC'
      } else if (type === 'RESOURCES' || type === 'ACCESSORY') {
        picType = 'SG'
      } else {
        picType = 'BC'
      }
      if (designSpace.length) {
        return [{ 'id': 'constCode', 'property': 'constCode', 'operator': '=', 'value': this.queryObj.constCode },
          { 'id': 'picType', 'property': 'picType', 'operator': '=', 'value': picType },
          { 'id': 'designSpace', 'property': 'designSpace', 'operator': 'in', 'value': designSpace },
          { 'id': 'schedule', 'property': 'schedule', 'operator': '=', 'value': 'F' }]
      } else {
        return [{ 'id': 'constCode', 'property': 'constCode', 'operator': '=', 'value': this.queryObj.constCode },
          { 'id': 'picType', 'property': 'picType', 'operator': '=', 'value': picType },
          { 'id': 'schedule', 'property': 'schedule', 'operator': '=', 'value': 'F' }]
      }
    },
    // 清空搜索条件
    clearSearch() {
      this.otherFilters = this.getCondition(this.queryObj.proConfigType)
    },
    // 获取搜索条件
    handleSearch(data) {
      this.currentPage = 1
      this.pageSize = 5
      const modelOtherFilter = data.filtersRaw.filter(item =>
        ['modelCode', 'categoryCode', 'seriesCode', 'recommendProgram', 'proPosition'].includes(item.property)
      )
      this.otherFilters = [...this.otherFilters, ...modelOtherFilter]
      this.getAllTableData(this.currentPage, this.pageSize, false, this.otherFilters)
    },
    // 获取表格数据
    getAllTableData(page, rows, onlyCountFlag, otherFilters) {
      const dataForm = new FormData()
      dataForm.append('page', page)
      dataForm.append('rows', rows)
      dataForm.append('onlyCountFlag', onlyCountFlag)
      dataForm.append('filtersRaw', JSON.stringify(otherFilters))
      queryPicTableData(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          if (!onlyCountFlag) {
            this.tableData = res.data.records
            this.total = res.data.total
            if (this.total <= this.currentPage * this.pageSize) {
              this.allTotal = this.total
            }
            const selectIds = this.selectedData.map(e => {
              return e.id
            })
            // 表格数据对比是否存在已选择数据并对其勾选
            this.tableData.forEach(item => {
              if (selectIds.includes(item.id)) {
                this.$nextTick(() => {
                  this.$refs.multipleTable.toggleRowSelection(item)
                })
              }
            })
            this.showSelectedData = this.selectedData
            this.showTableData = this.tableData
          } else {
            this.allTotal = res.data.total
            this.total = res.data.total
            this.currentPage = res.data.page
          }
        }
      })
    },
    // 前往第几页
    showEnter(ev) {
      this.jumpPage = ev.srcElement.value
      this.getTotal(this.jumpPage)
    },
    // 获取总数据条数
    newEnter() {
      this.getTotal(this.currentPage)
    },
    // 当操作在非第一页时，跳回第一页
    jumpToFirstPage() {
      this.currentPage = 1 // 不在第一页搜索时，调回第一页显示
      this.jumpPage = 1
      this.allTotal = 0
      this.total = 0
    },
    // 分页，获取下一页数据
    handleCurrentChange(currentPage) {
      this.jumpPage = currentPage
      this.currentPage = currentPage
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.getAllTableData(this.currentPage, this.pageSize, false, this.otherFilters)
    },
    // 分页数据获取---> this.$refs.chosenTable/multipleTable.clearSelection
    handleSizeChange(val) {
      this.pageSize = val
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.jumpToFirstPage()
      this.getAllTableData(this.currentPage, this.pageSize, false, this.otherFilters)
    },
    // 计算当前数据范围 如:1-20
    handlePageRange(size, currentPage) {
      const start = size * (currentPage - 1) + 1
      const end = size * currentPage
      const pageRange = `${start}-${end}`
      return pageRange
    },
    // 获取数据总条数
    getTotal(val) {
      if (this.allTotal !== 0) return
      let page = this.currentPage
      if (val) {
        page = val
      }
      this.getAllTableData(page, this.pageSize, true, this.otherFilters)
      this.$nextTick(() => {
        this.getAllTableData(page, this.pageSize, false, this.otherFilters)
      })
    },
    setTBIndex({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex
    },
    // onParams(data) {
    //   const modelOtherFilter = data.filtersRaw.filter(item =>
    //     ['modelCode', 'categoryCode', 'seriesCode', 'recommendProgram', 'proPosition'].includes(item.property)
    //   )
    //   this.otherFilters = [...this.otherFilters, ...modelOtherFilter]
    // },
    selectionChange(selection) {
      this.selections = selection
    },
    selectionAll(val) {
      const selectIds = this.selectedData.map(e => {
        return e.id
      })
      val.length &&
        val.forEach(item => {
          if (!selectIds.includes(item.id)) {
            this.selectedData = this.selectedData.concat(item)
          }
        })
      if (!val.length) {
        this.tableData.forEach(item => {
          this.selectedData.forEach((s, index) => {
            if (s.id === item.id) {
              this.selectedData.splice(index, 1)
            }
          })
        })
      }
      this.showSelectedData = this.selectedData
    },
    // 产品数据手动勾选
    selectTable(val, row) {
      if (this.selectedData.length > 0) {
        // 筛选已勾选的code
        const codeList = val.map(e => {
          return e.id
        })
        if (codeList.includes(row.id)) {
          // 判断是勾选还是取消
          this.selectedData = this.selectedData.concat(row)
        } else {
          this.selectedData.forEach((item, index) => {
            if (item.id === row.id) {
              this.selectedData.splice(index, 1)
            }
          })
        }
      } else {
        this.selectedData = val
      }
      this.showSelectedData = this.selectedData
      this.$nextTick(() => {
        this.selectedData.forEach(item => {
          this.$refs.chosenTable.toggleRowSelection(item, true)
        })
      })
    },
    // 产品数据手动勾选
    selectRow(row) {
      if (this.selectedData.length > 0) {
        const arr = JSON.parse(JSON.stringify(this.selectedData))
        // 筛选已勾选的code
        const codeList = arr.map(e => {
          return e.id
        })
        if (!codeList.includes(row.id)) {
          // 判断是勾选还是取消
          this.selectedData = arr.concat(row)
          this.$nextTick(() => {
            this.selectedData.forEach(item => {
              this.$refs.multipleTable.toggleRowSelection(item, true)
            })
          })
        } else {
          this.selectedData.forEach(item => {
            if (item.id === row.id) {
              this.$refs.multipleTable.toggleRowSelection(item, false)
            }
          })
          this.$nextTick(() => {
            this.selectedData.forEach((item, index) => {
              if (item.id === row.id) {
                this.selectedData.splice(index, 1)
              }
            })
          })
        }
      } else {
        this.selectedData.push(row)
        this.$nextTick(() => {
          this.selectedData.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        })
      }
      this.showSelectedData = this.selectedData
    },
    deleteChose(index, row) {
      this.selectedData.splice(index, 1)
      this.$nextTick(() => {
        this.tableData.forEach(e => {
          if (e.id === row.id) {
            this.$refs.multipleTable.toggleRowSelection(e, false)
          }
        })
      })
      this.showSelectedData = this.selectedData
    },
    cancelHandle() {
      this.dialogShow = false
    },
    submitPicData() {
      this.$emit('success', this.selectedData)
      this.dialogShow = false
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedData.filter(item => row.id === item.id)
      return (filterArr.length > 0) ? 'selected-highlight' : ''
    },
    changeTab(tab) {
      // this.$refs.searchForm.handleSearch()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>

